我使用gemini提取出了老师视频中展示的文档,非常好。因为老师确实没有给文档,blog里面也搜不到,幸好有了AI,帮我很大的忙。

Setup

  1. Install NodeJS and Database 前提是要安装nodejs和某种数据库,因为prisma通常是为关系型数据库构建的,所以NoSQL这些大部分都不能支持,只支持MongoDB。我按照老师的要求,安装了postgresql。

  2. npm init -y ,初始化项目。 npm i --save-dev prisma typescript ts-node @types/node nodemon , Install dependencies

  3. Create tsconfig.json

    这个是配置typescript相关的。

  4. npx prisma init --datasource-provider postgresql , Initial Prisma project

  5. Connect Database

    a. Install VSCode extension for Prisma

    b. Also talk about auto formatting and npx prisma format

    这里需要重点讲解一下,datasource db指的是Prisma orm该怎么样连接到数据库管理系统,provider指的是数据库管理系统的类型,可以是mysqlsqlite等等,url指的是连接数据库管理系统的哪一个数据库。

    在步骤4执行之后,会生成schema.prisma文件和.env文件,在.env文件里面,有一个DATABASE_URL的变量,这里存放的是数据库的地址。这个地址可以是本地数据库的地址,也可以是云服务器中数据库的地址。

    image-20251023105826226

    generator的作用是定义代码生成规则,provider指定用哪一个生成器,output自定义生成文件的输出目录。因为prisma的核心是“基于schema自动生成代码”,而generator就是“告诉prisma”要生成什么,怎么生成,生成到哪里“的关键配置。

    只有这样配置了,在代码中才能使用PrismaClient,来方便的操作数据库。

    url的格式是:postgresql://用户名:密码@主机:端口/数据库名,我的本地用户名默认是postgres,密码是123456,主机是localhost,端口是5432,数据库需要新建,打开powershell,输入psql -h localhost -p 5432 -U postgres,输入密码123456,然后输入create database prisma,这样就生成了一个名称为prisma的数据库。

    那么这里的url就写成这样DATABASE_URL="postgresql://postgres:123456@localhost:5432/prisma?schema=public",这里的?schema=public,它的意思是告诉 Prisma(或其他工具):默认使用 public 这个 schema 来查找表和执行查询。这涉及到postgresql的表结构,和MySQL是不一样的,先不用管。

    image-20251023113721320

    schema.prisma
    prisma generate
    generator 配置
    生成 Prisma Client
    ../generated/prisma/index.js + 类型
    在代码中使用: `new PrismaClient`

    image-20251023105930064

  6. Create User Schema with name

  7. npx prisma migrate dev --name init , Create/Run migration。这一步是为了将定义的model迁移到数据库中去,dev表示只在开发环境做这件事,--name init表示为这次操作设置名称,方便以后查看。 这一步执行之后,会在prisma文件夹里面生成一个migrations文件夹,里面就是迁移文件,这些文件将与postgresql交互并进行用户指定的修改。 与此同时,也对Prisma client进行了更新,这样使用prisma client的时候,就能够用到最新的数据库。 image-20251023114555093

  8. npm install @prisma/client - Install Client (Talk about how this also generates the client as well for us and how this generation happens every time you migrate as well and how you can create this generation your self with npx prisma generate)

     

    创建一个script.ts文件,就可以写代码了。

  9. await prisma.user.create({ data: { name: "Sally" } }) - Create new user

  10. await prisma.user.findMany() - Get all users

 

Schema

Data Sources

  1. Can only have one datasource in your database
  2. The provider represents what database to use
  3. The url represents the URL of the database
  4. Should store the URL in .env to avoid exposing database secrets and to make it easy to change from dev to production

Generators

  1. Must have at least one generator but can have more than one

  2. The provider represents what generator to use

    a. This can be any NPM library such as a GraphQL generator

Models

  1. Models represent all the information about your database such as tables, columns, enums, etc.
  2. Each model is represented by a number of fields

Fields

  1. Fields are composed of a name, type, and optional type modifiers and attributes

FieldTypes

  1. String

  2. Boolean

  3. Int

  4. BigInt

  5. Float

  6. Decimal

  7. DateTime

  8. Json

  9. Bytes

  10. Reference to another table (Post)

  11. Unsupported

    a. Special case for when you pull a database and it contains types that Prisma does not support

Field Type Modifiers

  1. []

    a. Turns the column into a list. When used on a reference type it creates all needed foreign keys and such

    b. Can only be used on scalar types if the DB supports it

  2. ?

    a. Makes a field optional

    b. Cannot be used with []

 

Field Attributes

  1. Attributes have two levels

    a. Field attributes apply to one field @

    b. Block attributes apply to the entire block @@

  2. @id

    a. All tables must have an id field or have a unique field

    b. Can be combined with @default

    i. autoincrement()

    ii. uuid()

  3. @@id

    a. Used to create composite ids @@id([FirstName, LastName])

  4. @default

    a. Can be passed a static value or a function such as now()

  5. @unique - Makes a field unique

  6. @@unique - Makes a combination of fields unique @@unique(authorId, postId)

  7. @@index - Create index on one or more fields @@index(authorId, postId)

  8. @updatedAt - Automatically sets a field to the current time when you update the row

  9. @relation

    a. The fields with relation types are not actually in the db

    b. One To Many

    c. One To One

    d. Many To Many

    e. The @relation field must take a field and references value.

    i. The field points to the field on the current model

    ii. The references points to the field on the other model the field value references

    f. If you have multiple relations on the same model you need to pass a name to the references attribute to disambiguate them

Enums

 

Possible Finished Schema

 

Client

  1. Automatically connects when you run the first query1
  2. Automatically disconnects when process ends2
  3. Manages connection pool so only ever need one instance of the client3

Create

  1. create

  2. createMany

Read

  1. findUnique - Can also include/select

  2. findFirst - Same as findMany but only gets first result

  3. findMany - Can also select/include

    a. distinct - Can do distinct queries

    b. take / skip - Can do pagination

    c. orderBy - Can do sorting

Basic Filtering

  1. equals - same as not using an object
  2. not - { not: { name: "Kyle" } }
  3. in - { name: { in: ["Kyle", "Sally"] } }
  4. notIn
  5. lt / lte
  6. gt / gte
  7. contains - { email: { contains: "@gmail.com" } }
  8. startsWith / endsWith
  9. AND - { AND: [{ name: "Kyle" }, { age: 27 }] }
  10. OR
  11. NOT

Relation Filtering

  1. some
  2. every
  3. none
  4. is
  5. isNot

Update

  1. update - Can also include/select

    a. Only updates 1 record

    b. Must include data and where

Number Operations

  1. increment

  2. decrement

  3. multiply

  4. divide

Relation Connect/Disconnect

  1. Should I cover this

  2. https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#nested-writes

  3. updateMany - Same as update but with no select/include

Delete

  1. delete - Can also select/include

    a. Only deletes 1 record

  2. deleteMany - Can also select/include

    a. Only deletes 1 record